package com.rzt.cft.service.cms.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rzt.cft.entity.cms.CmsResource;
import com.rzt.cft.mapper.cms.CmsResourceMapper;
import com.rzt.cft.service.cms.ICmsResourceService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 基础-资源信息 服务实现类
 * </p>
 *
 * @author zhongzhong
 * @since 2020-03-10
 */
@Service
public class CmsResourceServiceImpl extends ServiceImpl<CmsResourceMapper, CmsResource> implements ICmsResourceService {

    @Value("${uploadFile.path}")
    private String uploadPath;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        String yyyyMMdd = uploadPath + File.separator + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + File.separator;
        if (!FileUtil.exist(yyyyMMdd)) {
            FileUtil.mkdir(yyyyMMdd);
        }
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File file1 = FileUtil.writeBytes(file.getBytes(), yyyyMMdd + fileName);
        CmsResource cmsResource = new CmsResource();
        if (file1.length() > 0) {
            cmsResource.setFileSuffix(suffix);
            cmsResource.setPath(yyyyMMdd.replaceAll("\\\\", "/"));
            cmsResource.setFileKey(fileName);
            cmsResource.setTitle(file.getOriginalFilename());
            baseMapper.insert(cmsResource);
        }
        return cmsResource.getId();
    }
}
